package com.example.blogemail.listener;

import com.alibaba.fastjson.JSON;
import com.example.blogemail.eneity.Email;
import com.example.blogemail.mapper.EmailErrorMapper;
import com.example.blogemail.service.emailService;
import com.rabbitmq.client.Channel;
import com.sun.org.apache.bcel.internal.generic.IfInstruction;
import com.yz.core.dto.EmailDto;
import com.yz.core.utils.EmailUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @className: EmailQueueListen
 * @author: shuishui
 * @date: 2023/02/03 12:40
 */
@Component
@Slf4j
public class EmailQueueListener {
    @Autowired
    private emailService emailService;
    @RabbitListener(queues = "email-work")
    public void consuemrMsg(EmailDto emailDto, Channel channel, Message message){
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            sendMsg(emailDto);
            channel.basicAck(deliveryTag,false);//发送标识，批量处理为flase
        } catch (Exception e) {
            log.error("Email:迷路到路了QAQ",e);
            boolean result = saveDB(emailDto);
            if (result) {
                try {
                    channel.basicAck(deliveryTag,false);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }else{
                try {
                    channel.basicNack(deliveryTag,false,true);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    private boolean saveDB(EmailDto emailDto) {
        Email email = new Email();
        email.setCreatTime(new Date());
        email.setStatus(1);
        email.setEmailText(JSON.toJSONString(emailDto));
        return emailService.save(email);
    }

    private void sendMsg(EmailDto emailDto) throws Exception {
        EmailUtils.sendEmailInfoUser(emailDto);
//        int x= 10/0;
    }
}
